#include "serverconmanager.h"
#include "../common/comiocontroller.h"

ServerConManager* ServerConManager::_instance = NULL;

ServerConManager::ServerConManager(QObject *parent) :
    QObject(parent)
{
    ///listen new connection
    connect(&m_cListener, SIGNAL(newConnection()),SLOT(slot_clientConnected()));
}

ServerConManager* ServerConManager::getInstance()
{
    if(_instance == NULL)
        _instance = new ServerConManager();
    return _instance;
}


bool ServerConManager::startListening(unsigned int iPort)
{
    return m_cListener.listen(QHostAddress::Any, iPort);
}

void ServerConManager::slot_clientConnected()
{    




    QTcpSocket* pcClientSocket = m_cListener.nextPendingConnection();
    if(pcClientSocket == NULL) {
        ComIOController::getInstance()->msgOutput("<ServerConManager::newClientConnected>:no connection found.");
    }else if(m_cClients.size() > 0) {
        //TODO only one clienct connection at one time
        ComIOController::getInstance()->msgOutput("<ServerConManager::newClientConnected>:connection rejected. server in used.");
        //pcClientSocket->
    }else{
        ServerClient* pcClient = new ServerClient(pcClientSocket);
        connect(pcClient, SIGNAL(sig_disconnected(ServerClient*)), this, SLOT(slot_clientDisconnected(ServerClient*)));
        m_cClients.push_back(pcClient);
        ComIOController::getInstance()->msgOutput("<ServerConManager::newClientConnected>:new connection established.");
    }
    return;
}

void ServerConManager::slot_clientDisconnected(ServerClient* pcClient)
{
    for(int i = 0; i < m_cClients.size(); i++) {
        if(m_cClients[i] == pcClient) {
            disconnect(pcClient, SIGNAL(sig_disconnected(ServerClient*)), this, SLOT(slot_clientDisconnected(ServerClient*)));
            m_cClients[i]->deleteLater();
            m_cClients.remove(i);
            ComIOController::getInstance()->msgOutput("<ServerConManager::slot_clientDisconnected>:deleted connection record.");
        }
    }
}
